// 法律援助平台项目专用 API 使用示例
import { authAPI, caseAPI, lawyerAPI, userAPI, commonAPI } from '@/api'
import { useUserAuthStore, useCaseStore, useLawyerStore } from '@/stores'
import { ElMessage } from 'element-plus'

// 1. 用户认证流程示例
export const authExamples = {
  // 用户登录
  async userLogin(username, password) {
    try {
      const response = await authAPI.login({ username, password })
      ElMessage.success('登录成功')
      return response
    } catch (error) {
      ElMessage.error('登录失败：' + error.message)
      throw error
    }
  },

  // 用户注册
  async userRegister(userData) {
    try {
      const response = await authAPI.register(userData)
      ElMessage.success('注册成功，请登录')
      return response
    } catch (error) {
      ElMessage.error('注册失败：' + error.message)
      throw error
    }
  },

  // 用户登出
  async userLogout() {
    try {
      await authAPI.logout()
      ElMessage.success('已安全退出')
    } catch (error) {
      console.error('登出失败:', error)
      // 即使API失败也要清除本地状态
      const userAuthStore = useUserAuthStore()
      userAuthStore.logout()
    }
  },

  // 检查登录状态
  checkLoginStatus() {
    const userAuthStore = useUserAuthStore()
    return userAuthStore.isLogin
  }
}

// 2. 案件管理流程示例
export const caseExamples = {
  // 创建新案件
  async createNewCase(caseData) {
    try {
      const response = await caseAPI.createCase({
        type: caseData.type,
        description: caseData.description,
        priority: caseData.priority || 'normal',
        clientInfo: caseData.clientInfo
      })
      ElMessage.success('案件创建成功')
      return response
    } catch (error) {
      ElMessage.error('创建案件失败：' + error.message)
      throw error
    }
  },

  // 上传案件材料
  async uploadCaseMaterial(caseId, file, materialType) {
    try {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', materialType)
      formData.append('description', file.name)

      const response = await caseAPI.uploadMaterial(caseId, formData)
      ElMessage.success('材料上传成功')
      return response
    } catch (error) {
      ElMessage.error('材料上传失败：' + error.message)
      throw error
    }
  },

  // 获取用户案件列表
  async loadUserCases(page = 1, status = '') {
    try {
      const params = { page, pageSize: 10 }
      if (status) params.status = status
      
      const response = await caseAPI.getCaseList(params)
      return response
    } catch (error) {
      ElMessage.error('获取案件列表失败：' + error.message)
      throw error
    }
  },

  // 更新案件状态
  async updateCaseStatus(caseId, newStatus) {
    try {
      await caseAPI.updateCaseStatus(caseId, newStatus)
      ElMessage.success('案件状态更新成功')
    } catch (error) {
      ElMessage.error('更新案件状态失败：' + error.message)
      throw error
    }
  }
}

// 3. 律师工作台示例
export const lawyerExamples = {
  // 加载律师资料
  async loadLawyerProfile() {
    try {
      await lawyerAPI.getProfile()
      ElMessage.success('律师资料加载成功')
    } catch (error) {
      ElMessage.error('加载律师资料失败：' + error.message)
      throw error
    }
  },

  // 接受案件
  async acceptCase(caseId) {
    try {
      await lawyerAPI.acceptCase(caseId)
      ElMessage.success('案件接受成功')
    } catch (error) {
      ElMessage.error('接受案件失败：' + error.message)
      throw error
    }
  },

  // 更新案件进度
  async updateCaseProgress(caseId, status, note) {
    try {
      await lawyerAPI.updateCaseProgress(caseId, { status, note })
      ElMessage.success('进度更新成功')
    } catch (error) {
      ElMessage.error('更新进度失败：' + error.message)
      throw error
    }
  },

  // 添加日程安排
  async addScheduleEvent(eventData) {
    try {
      await lawyerAPI.addScheduleEvent({
        date: eventData.date,
        title: eventData.title,
        description: eventData.description,
        type: eventData.type || 'meeting'
      })
      ElMessage.success('日程添加成功')
    } catch (error) {
      ElMessage.error('添加日程失败：' + error.message)
      throw error
    }
  }
}

// 4. 用户中心示例
export const userExamples = {
  // 更新用户信息
  async updateUserProfile(profileData) {
    try {
      await userAPI.updateUserInfo(profileData)
      ElMessage.success('个人信息更新成功')
    } catch (error) {
      ElMessage.error('更新个人信息失败：' + error.message)
      throw error
    }
  },

  // 上传头像
  async uploadAvatar(file) {
    try {
      const formData = new FormData()
      formData.append('avatar', file)
      
      const response = await userAPI.uploadAvatar(formData)
      ElMessage.success('头像上传成功')
      return response.avatarUrl
    } catch (error) {
      ElMessage.error('头像上传失败：' + error.message)
      throw error
    }
  },

  // 获取用户消息
  async getUserMessages(page = 1) {
    try {
      const response = await userAPI.getUserMessages({ page, pageSize: 20 })
      return response
    } catch (error) {
      ElMessage.error('获取消息失败：' + error.message)
      throw error
    }
  }
}

// 5. 通用功能示例
export const commonExamples = {
  // 文件上传
  async uploadFile(file, type = 'document') {
    try {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', type)
      
      const response = await commonAPI.uploadFile(formData)
      return response.fileUrl
    } catch (error) {
      ElMessage.error('文件上传失败：' + error.message)
      throw error
    }
  },

  // 获取案件类型
  async getCaseTypes() {
    try {
      const response = await commonAPI.getCaseTypes()
      return response
    } catch (error) {
      console.error('获取案件类型失败:', error)
      // 返回默认类型
      return [
        { value: 'civil', label: '民事案件' },
        { value: 'criminal', label: '刑事案件' },
        { value: 'administrative', label: '行政案件' }
      ]
    }
  },

  // 搜索功能
  async searchContent(keyword, category = 'all') {
    try {
      const response = await commonAPI.search({
        keyword,
        category,
        page: 1,
        pageSize: 20
      })
      return response
    } catch (error) {
      ElMessage.error('搜索失败：' + error.message)
      throw error
    }
  }
}

// 6. 组合使用示例
export const combinedExamples = {
  // 完整的案件创建流程
  async completeCaseCreation(caseData, materials) {
    try {
      // 1. 创建案件
      const caseResponse = await caseExamples.createNewCase(caseData)
      
      // 2. 上传材料
      const materialPromises = materials.map(material => 
        caseExamples.uploadCaseMaterial(caseResponse.id, material.file, material.type)
      )
      await Promise.all(materialPromises)
      
      // 3. 更新案件状态为已提交
      await caseExamples.updateCaseStatus(caseResponse.id, 'submitted')
      
      ElMessage.success('案件创建完成，已提交审核')
      return caseResponse
    } catch (error) {
      ElMessage.error('案件创建流程失败：' + error.message)
      throw error
    }
  },

  // 律师处理案件流程
  async lawyerProcessCase(caseId, actions) {
    try {
      const lawyerStore = useLawyerStore()
      
      // 1. 接受案件
      await lawyerExamples.acceptCase(caseId)
      
      // 2. 更新进度
      if (actions.progress) {
        await lawyerExamples.updateCaseProgress(
          caseId, 
          actions.progress.status, 
          actions.progress.note
        )
      }
      
      // 3. 添加相关日程
      if (actions.schedule) {
        await lawyerExamples.addScheduleEvent({
          date: actions.schedule.date,
          title: `处理案件 ${caseId}`,
          description: actions.schedule.description
        })
      }
      
      ElMessage.success('案件处理流程完成')
    } catch (error) {
      ElMessage.error('案件处理失败：' + error.message)
      throw error
    }
  }
}

// 7. 错误处理和重试机制
export const errorHandlingExamples = {
  // 带重试的API调用
  async retryApiCall(apiCall, maxRetries = 3) {
    let lastError
    for (let i = 0; i < maxRetries; i++) {
      try {
        return await apiCall()
      } catch (error) {
        lastError = error
        if (i < maxRetries - 1) {
          console.log(`API调用失败，${i + 1}秒后重试...`)
          await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)))
        }
      }
    }
    throw lastError
  },

  // 网络状态检查
  checkNetworkStatus() {
    return navigator.onLine
  },

  // 离线数据处理
  handleOfflineData() {
    if (!this.checkNetworkStatus()) {
      ElMessage.warning('当前处于离线状态，部分功能可能受限')
      return false
    }
    return true
  }
}

// 8. 导出所有示例
export const projectAPIExamples = {
  auth: authExamples,
  case: caseExamples,
  lawyer: lawyerExamples,
  user: userExamples,
  common: commonExamples,
  combined: combinedExamples,
  errorHandling: errorHandlingExamples
} 